import $system from './system.js';
import $dialog from './dialog.js';
const goObject = {
	pageUrl:'',
	target:'',
	router:{},
	loginState:false,
	noLoginPages:{},
	_parse(url,query=false){
		if (!url || typeof url !=='string'){
			return '';
		}
		if (url.indexOf('.')>0 && url.indexOf('/')<0){
			let s = url.split('.');
			s[0] = s[0].toLowerCase() in this.router?this.router[s[0].toLowerCase()]:s[0];
			url = s.join('/');
		}
		
		if (query){
			let params=[];
			if (typeof query ==='string'){
				url = url+url.indexOf('?')>=0?'&':'?'+query;
			}else{
				for(let k in query){
					params.push(k +'='+this.query[k]);
				}
				url = url+url.indexOf('?')>=0?'&':'?'+params.join('&');
			}
			
		}
		return url.indexOf('/pages/')>=0?url:'/pages/'+url;
	},
	setLoginState(state){
		this.loginState = state;
	},
	noLogin(pages){
		let url = '';
		for (var i = 0; i < pages.length; i++) {
			url = this._parse(pages[i]);
			if (url){
				this.noLoginPages[url] = true;
			}
			
		}
	},
	_check(url){
		url = this._parse(url);
		if (!url){
			return false;
		}
		let result =  this.loginState || this._parse(url) in this.noLoginPages;
		if (!result){
			let that = this;
			url = this._parse('user.login');
			uni.navigateTo({
				url: url,
				fail: function(err) {
					uni.switchTab({
						url: url
					});
				}
			});	
		}
		return result;
	},
	getOption(option,query){
		if (option.scene){
			const str = decodeURIComponent(option.scene).replace('?', '&')
			if (str.indexOf('=')<0){
				query['scene'] = str;
			}else{
				//变成缩写 union_i = ui;
				let map = {};
				let keys = Object.keys(query);
				for (let i = 0; i <keys.length ; i++) {
					let k= keys[i].split("_");
					let key = '';
					for(let j=0;j<k.length;j++){
						if (k[j]){
							key = key + k[j][0];//首字母
						}
					}
					map[key] = keys[i];
				
				}
				let ary;
				let strArr = str.split('&');
				
				for (var i = strArr.length - 1; i >= 0; i--) {
					ary= strArr[i].split("=");
					if (ary.length>1){
						option[map[ary[0]]?map[ary[0]]:ary[0]] = ary[1];
					}
				}
			}
		}
		let keys = Object.keys(query);
		for (let i = 0; i <keys.length ; i++) {
			if (option[keys[i]]){
				query[keys[i]] = option[keys[i]];
			}
		
		}
	},
	back(delay = 0,data=false) {
		if (data){
			uni.$emit('back_data',data);		
		}
		if (delay>0){
			setTimeout(function(){
				uni.navigateBack({})
				clearTimeout();
			},delay);
		}else{
			uni.navigateBack({
				
			});
		}
		
	},
	to(url,query=false){
		if (!this._check(url)){
			return false;
		}
		let that = this;
		uni.navigateTo({
			url: this._parse(url,query),
			fail: function(err) {
				uni.switchTab({
					url: that._parse(url,query)
				});
			}
		});	
	},
	url(url,title=''){
		//console.log('url',url);
		uni.navigateTo({
			url: '/pages/index/webview?type=url&title='+title+'&url='+url
		});
	},
	html(url,title=''){
		//console.log('url',url);
		uni.navigateTo({
			url: '/pages/index/webview?type=html&title='+title+'&url='+url
		});
	},
	launch(url,query=false){
		//console.log('url',url);
		if (!this._check(url)){
			return false;
		}
		uni.reLaunch({
			url: this._parse(url,query)
		});
	},
	redirect(url,query=false){
		if (!this._check(url)){
			return false;
		}
		let that = this;
		uni.redirectTo({
			url: this._parse(url,query),
			fail: function(err) {
				uni.switchTab({
					url: that._parse(url,query)
				});
			}
		});	
	},	
		
	tab(url,query=false){
		if (!this._check(url)){
			return false;
		}
		//console.log('url',url);
		uni.switchTab({
			url: this._parse(url,query)
		});
	},
	page(page,type='',title='',remark='') {
		//console.log(page)
		if (!page){
			return false;
		}
		let that =this;
		let content = '';
		let url = page;
		if (typeof page === 'object'){
			url = page.url || '';
			type = page.type || type;
			title = page.title || title;
			remark = page.remark || remark;
			content = page.content || url;
			if (page.params && url){
				url = url + url.indexOf('?')>=0?'&':'?';
				for (let i in page.params) {
					url = url + page.params[i].key + '=' + page.params[i].value + '&'
				}
			}
			
		}

		if (type==='qrcode'){
			uni.navigateTo({
				url: '/pages/user/qrcode?url='+url+'&title='+(title||'')+'&remark='+(remark||'')
			})	
		} else if (type==='html') {
			uni.navigateTo({
				url: '/pages/index/webview?type=html&url='+url+'&title='+(title||'')
			})
		} else if (type==='url' || (url && typeof url === 'string' && (url.startsWith('http://') || url.startsWith('https://')))) {
			uni.navigateTo({
				url: '/pages/index/webview?type=url&url='+url+'&title='+(title||'')
			})
		} else if (type==='tab') {
			if (!this._check(url)){
				return false;
			}
			uni.switchTab({
				url: this._parse(url)
			});
		} else if (type==='to') {
			if (!this._check(url)){
				return false;
			}
			uni.redirectTo({
				url: that._parse(url),
				fail: function(err) {
					uni.switchTab({
						url: that._parse(url)
					});
				}
			});		
		}else if (type==='launch') {
			if (!this._check(url)){
				return false;
			}
			uni.reLaunch({
				url: that._parse(url),
				fail: function(err) {
					uni.switchTab({
						url: that._parse(url)
					});
				}
			});	
		}else if (type==='back') {
			this.back();
		}else if (type==='toast') {
			$dialog.toast(content);
		}else if (type==='help') {
			$dialog.help(content);
		}else if (type==='error') {
			$dialog.error(content);
		}else if (type==='call') {
			this.call(url);
		}else if (type==='copy') {
			$system.copy(url);
		}else if (type==='eval') {
			let pages = getCurrentPages();

			if (pages && pages.length>0){
				this.$page = pages[pages.length-1];
			}else{
				this.$system = $system;
			}
			eval(url);
		} else {
			if (!this._check(url)){
				return false;
			}
			uni.navigateTo({
				url: that._parse(url),
				fail: function(err) {
					uni.switchTab({
						url: that._parse(url)
					});
				}
			})
		}

	},
	call(phone) {
		uni.makePhoneCall({
			phoneNumber:phone.toString(),//电话号码
			success:function(e){
				//console.log('e',e);
			},
			fail:function(e){
				//console.log('e',e);
			}
		})
	},
	location(){
		// #ifdef APP-PLUS || MP 
		let routes = getCurrentPages(); //获取当前页面栈
		let curRoute='';
		let params = '';
		if (routes && routes.length>0){
			curRoute = routes[routes.length - 1].route;
			let options = routes[routes.length - 1].options;
			
			for (let key in options){
				params += (!params?'?':'&')+key+'='+options[key];
			}
			
		}
		return curRoute+params;
		//#endif
		// #ifdef H5 
		var url = window.location.href.replace(window.location.origin,'');
		if (url && url.startsWith('/')){
			url = url.substring(1);
		}	
		if (url && url.startsWith('#')){
			url = url.substring(1);
		}
		if (url && url.startsWith('/')){
			url = url.substring(1);
		}
		return url;
		// #endif
	},
	
	map(src,dst){
		this.router[src.toLowerCase()]=dst;
	},
	setPage(page){
		this.pageUrl = page.toLowerCase() in this.router?this.router[page.toLowerCase()]:page;
	}

}

const proxy = obj => { // 递归代理器
	return new Proxy(obj, {
		apply: function(fun, thisArg, argumentsList) {
			//console.log('argumentsList',argumentsList);
			let page = goObject.pageUrl;
			let target = goObject.target;
			goObject.pageUrl = '';
			goObject.target = '';
			let url = (page?page.toLowerCase()+'/':'')+target;
			if (!page){
				let count = 0;let s = '';
				for(let i=0;i<target.length;i++){
					if(target[i] >= 'A' && target[i] <= 'Z'){ 
						s = s + '/'+ target[i].toLowerCase();
						count++;
					}else{
						s = s + target[i];
					}
				}
				if (count>0){
					url = s;
				}else if (target.indexOf('_')>=0){
					url = target.replace('_','/');
				}else{
					url = target +'/index';
				}
			}
			let params = '';
			for(let i=0;i<argumentsList.length;i++){
				let arg = argumentsList[i];
				if (arg.constructor == Object){
					for( let p in argumentsList[i]){
						let arg2=argumentsList[i][p];
						params = params +(params?'&':'') + p+ '=' +(arg2 instanceof Object?JSON.stringify(arg2):arg2);
					}
				}else{
					params = params + arg;
				}
			}
			if (params){
				url = url + ((url.indexOf('?')>=0)?'&':'?')+params;
			}
			console.log('url',url);
			return goObject.to(url);
		  },
		  get(target, key, receiver) {
			
			if (key in target){
				return target[key]
			}else{
				if (key[0] >= 'A' && key[0] <= 'Z'){
					goObject.setPage(key);
					return proxy(goObject);
				}else{
					goObject.target = key;
					return proxy(goObject.to);
				}
			}
		  	
		  }
	});
}

export default proxy(goObject);